﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Windows.Forms;

namespace FxSuperCore.Utils
{
	/// <summary>
	/// 依赖扫描注册类
	/// </summary>
	public static class DependencyPathRegister
	{
		private static LinkedList<string> depyPaths = new LinkedList<string>();

		/// <summary>
		/// 程序可执行文件所在目录
		/// </summary>
		public static string AppPath => Path.GetDirectoryName(Application.ExecutablePath);

		static DependencyPathRegister()
		{
			AppDomain.CurrentDomain.AssemblyResolve += CurrentDomainAssemblyResolve;
		}

		/// <summary>
		/// 动态加载
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="args"></param>
		/// <returns></returns>
		private static Assembly CurrentDomainAssemblyResolve(object sender, ResolveEventArgs args)
		{
			foreach (string folder in depyPaths)
			{
				string path = Path.Combine(folder, args.Name.Split(',')[0]) + ".dll";
				if (File.Exists(path))
				{
					return Assembly.LoadFrom(path);
				}
			}
			return null;
		}

		/// <summary>
		/// 注册一个dll扫描路径
		/// </summary>
		/// <param name="folder">dll扫描路径</param>
		public static void RegisterDependencyPath(string folder)
		{
			if (!Directory.Exists(folder))
			{
				throw new DirectoryNotFoundException($"[{folder}]不存在");
			}

			depyPaths.AddLast(folder);
		}
	}
}
